package com.byx.chatclient.view.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.AnimationDrawable;
import android.media.MediaMetadataRetriever;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.byx.chatclient.ChatApp;
import com.byx.chatclient.R;
import com.byx.chatclient.adapter.ChatAdapter;
import com.byx.chatclient.contract.home.ChatTaskContract;
import com.byx.chatclient.entity.Constant;
import com.byx.chatclient.entity.Friend;
import com.byx.chatclient.entity.MessagePo;
import com.byx.chatclient.entity.message.AudioMsgBody;
import com.byx.chatclient.entity.message.FileMsgBody;
import com.byx.chatclient.entity.message.ImageMsgBody;
import com.byx.chatclient.entity.message.Message;
import com.byx.chatclient.entity.message.MsgBody;
import com.byx.chatclient.entity.message.MsgSendStatus;
import com.byx.chatclient.entity.message.MsgType;
import com.byx.chatclient.entity.message.TextMsgBody;
import com.byx.chatclient.entity.message.VideoMsgBody;
import com.byx.chatclient.event.MessageEvent;
import com.byx.chatclient.http.HttpFilesUtil;
import com.byx.chatclient.im.AbstractMessageSender;
import com.byx.chatclient.im.ImClientBoot;
import com.byx.chatclient.im.MessageConverter;
import com.byx.chatclient.presenter.home.SingleChatPresenter;
import com.byx.chatclient.utils.BottomEditUiHelper;
import com.byx.chatclient.utils.FileUtils;
import com.byx.chatclient.utils.GradientStatusBarUtil;
import com.byx.chatclient.utils.LogUtil;
import com.byx.chatclient.utils.OpenFileUtil;
import com.byx.chatclient.utils.PictureFileUtil;
import com.byx.chatclient.utils.ThreadPoolUtil;
import com.byx.chatclient.widget.BigImageView;
import com.byx.chatclient.widget.MediaManager;
import com.byx.chatclient.widget.RecordButton;
import com.byx.chatclient.widget.Toolbar;
import com.byx.imclientutil.listener.OnMessageStatusListener;
import com.google.gson.JsonObject;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.entity.LocalMedia;
import com.nbsp.materialfilepicker.ui.FilePickerActivity;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

import butterknife.BindView;
import butterknife.OnClick;
import tv.danmaku.ijk.media.player.IjkMediaPlayer;

/**
 * @author Superb
 */
@SuppressLint("NonConstantResourceId")
public class SingleChatActivity extends BaseActivity<SingleChatPresenter> implements ChatTaskContract.View, SwipeRefreshLayout.OnRefreshListener, OnMessageStatusListener {
    private static final String TAG = SingleChatActivity.class.getSimpleName();

    @BindView(R.id.tb_toolbar_chat)
    protected Toolbar mTbChat;
    @BindView(R.id.et_message)
    protected EditText mEtMessage;
    @BindView(R.id.btn_send)
    protected Button mBtnSend;
    @BindView(R.id.rv_chat_message_list)
    protected RecyclerView mRvChatMsgList;
    @BindView(R.id.swipe_refresh_layout)
    protected SwipeRefreshLayout mSwipeRefreshLayout;
    @BindView(R.id.iv_emoji)
    protected ImageView mIvEmoji;
    @BindView(R.id.rl_bottom_layout)
    protected RelativeLayout mBottomLayout;
    @BindView(R.id.ll_emotion)
    protected LinearLayout mLlEmotion;
    @BindView(R.id.ll_content)
    protected LinearLayout mLlContent;
    @BindView(R.id.ll_add)
    protected LinearLayout mLlAdd;
    @BindView(R.id.iv_add)
    protected ImageView mIvAdd;
    @BindView(R.id.iv_audio)
    protected ImageView mIvAudio;
    @BindView(R.id.btn_audio)
    protected RecordButton mBtnAudio;

    private ImageView mIvMsgAudio;

    private Friend mCurrentFriend;
    private String mSenderId;

    private ChatAdapter mAdapter;
    private final String userRemoteAvatarUrl = ChatApp.getInstance().getUserPo().getRemoteAvatarUrl();

    public static final int REQUEST_CODE_IMAGE=0;
    public static final int REQUEST_CODE_VIDEO =1;
    public static final int REQUEST_CODE_FILE=2;

    @Override
    protected SingleChatPresenter createPresenter() {
        return new SingleChatPresenter(this);
    }

    @Override
    protected void setRootView(Bundle savedInstanceState) {
        setContentView(R.layout.activity_chat);
    }

    @Override
    protected void initialize() {
        GradientStatusBarUtil.getInstance().bind(this).withBackgroundResource(R.drawable.toolbar).init();

        EventBus.getDefault().register(this);

        Intent intent = getIntent();
        mSenderId = ((ChatApp) getApplication()).getUserPo().getLoginId();
        mCurrentFriend = (Friend) intent.getSerializableExtra(Constant.INTENT_KEY_FRIEND);

        mAdapter = new ChatAdapter(SingleChatActivity.this,mSenderId,true);
        mRvChatMsgList.setAdapter(mAdapter);

        String currentObjectId;

        currentObjectId = mCurrentFriend.getFriendLoginId();
        mTbChat.setTitle(mCurrentFriend.getFriendRemarkName());
        mTbChat.setSubtitle(mCurrentFriend.getStatus() == 200 ? "在线" : "离线");
        mTbChat.setNavigationOnClickListener(v -> finish());

        List<MessagePo> chatList = presenter.getSingleChatMsg(mSenderId, currentObjectId);
        //将从数据库取出的消息列表转换为用于显示的消息列表
        List<Message> messageList = chatList.stream().map(MessageConverter::toMessage).collect(Collectors.toList());
        mAdapter.addData(0,messageList);
        mAdapter.setOnItemChildClickListener((adapter, view, position) -> {
            switch (view.getId()){
                case R.id.rlAudio:
                    AudioMsgBody audioMsgBody = (AudioMsgBody) mAdapter.getItem(position).getBody();
                    System.out.println(audioMsgBody.getLocalPath());
                    if (!FileUtils.isFileExists(audioMsgBody.getLocalPath())){
                        HttpFilesUtil.download(audioMsgBody.getLocalPath(), audioMsgBody.getRemoteUrl(), new HttpFilesUtil.DownloadCallBack() {
                            @Override
                            public void onSuccess() {
                                playAudioMsg(view,mAdapter.getItem(position));
                            }

                            @Override
                            public void onFailure(Throwable t) {
                                t.printStackTrace();
                            }
                        });
                    }else {
                        playAudioMsg(view,mAdapter.getItem(position));
                    }
                    break;
                case R.id.bivPic:
                    Message message = mAdapter.getItem(position);
                    if (message.getMsgType().equals(MsgType.IMAGE)){
                        ImageMsgBody imageMsgBody = (ImageMsgBody) message.getBody();
                        if (TextUtils.isEmpty(imageMsgBody.getThumbUrl())){
                            String name = imageMsgBody.getRemoteUrl().substring(imageMsgBody.getRemoteUrl().lastIndexOf('/'));
                            HttpFilesUtil.download(ChatApp.IMAGE_DIR + name, imageMsgBody.getRemoteUrl(), new HttpFilesUtil.DownloadCallBack() {
                                @Override
                                public void onSuccess() {
                                    imageMsgBody.setThumbUrl(ChatApp.IMAGE_DIR + name);
                                    BigImageView.create(SingleChatActivity.this).showPhotoViewWithGlide(imageMsgBody.getThumbUrl());
                                    presenter.saveChatMsg(MessageConverter.toMessagePo(message,true));
                                }

                                @Override
                                public void onFailure(Throwable t) {

                                }
                            });
                        }else {
                            BigImageView.create(SingleChatActivity.this).showPhotoViewWithGlide(imageMsgBody.getThumbUrl());
                        }
                    }else if (message.getMsgType().equals(MsgType.VIDEO)){
                        VideoMsgBody videoMsgBody = (VideoMsgBody) message.getBody();
                        String url;
                        if (FileUtils.isFileExists(videoMsgBody.getLocalPath())){
                            url = videoMsgBody.getLocalPath();
                        }else {
                            url = videoMsgBody.getRemoteUrl();
                        }
                        Intent it = new Intent(SingleChatActivity.this, VideoPlayerActivity.class);
                        it.putExtra(VideoPlayerActivity.INTENT_VIDEO_PATH, url);
                        startActivity(it);
                    }
                    break;
                case R.id.rc_msg_canceled:
                    Message msg = mAdapter.getItem(position);
                    FileMsgBody body = (FileMsgBody) msg.getBody();
                    if (FileUtils.isFileExists(body.getLocalPath())){
                        OpenFileUtil.openFiles(SingleChatActivity.this,body.getLocalPath());
                    }else {
                        ((TextView) view).setText("下载中");
                        String path = ChatApp.FILES_DIR + File.separator + body.getDisplayName();
                        if (FileUtils.createOrExistsFile(path)){
                            HttpFilesUtil.download(path, body.getRemoteUrl(), new HttpFilesUtil.DownloadCallBack() {
                                @Override
                                public void onSuccess() {
                                    ((TextView) view).setText("打开");
                                    body.setLocalPath(path);
                                    presenter.saveChatMsg(MessageConverter.toMessagePo(msg,true));
                                }

                                @Override
                                public void onFailure(Throwable t) {
                                    ((TextView) view).setText("下载失败");
                                }
                            });
                        }
                    }
                    break;
                default:break;
            }
        });

        mRvChatMsgList.setLayoutManager(new LinearLayoutManager(this));
        mRvChatMsgList.scrollToPosition(mAdapter.getItemCount() - 1);

        mSwipeRefreshLayout.setOnRefreshListener(null);

        ImClientBoot.getInstance().setOnMessageStatusListener(this);
    }

    @SuppressLint("ClickableViewAccessibility")
    @Override
    protected void setListeners() {
        final BottomEditUiHelper mUiHelper = BottomEditUiHelper.with(this)
                .bindSendButton(mBtnSend)
                .bindToEmojiButton(mIvEmoji)
                .bindMessageEditText(mEtMessage)
                .bindBottomLayout(mBottomLayout)
                .bindEmotionLayout(mLlEmotion)
                .bindContentLayout(mLlContent)
                .bindAudioButton(mBtnAudio)
                .bindAudioImageView(mIvAudio)
                .bindToAddButton(mIvAdd)
                .bindAddLayout(mLlAdd)
                .bindEmojiData();
        mRvChatMsgList.addOnLayoutChangeListener((v, left, top, right, bottom, oldLeft, oldTop, oldRight, oldBottom) -> {
            if (bottom < oldBottom) {
                mRvChatMsgList.post(() -> {
                    if (mAdapter.getItemCount() > 0) {
                        mRvChatMsgList.smoothScrollToPosition(mAdapter.getItemCount() - 1);
                    }
                });
            }
        });
        //点击空白区域关闭键盘
        mRvChatMsgList.setOnTouchListener((view, motionEvent) -> {
            mUiHelper.hideBottomLayout(false);
            mUiHelper.hideSoftInput();
            mEtMessage.clearFocus();
            mIvEmoji.setImageResource(R.mipmap.ic_emoji);
            return false;
        });
        mBtnAudio.setOnFinishedRecordListener((audioPath, time) -> {
            Log.d(TAG, "录音结束回调");
            File file = new File(audioPath);
            if (file.exists()) {
                sendAudioMessage(audioPath,time);
            }
        });
    }

    @SuppressLint("NonConstantResourceId")
    @OnClick({R.id.btn_send,R.id.ll_photo,R.id.ll_video,R.id.ll_location,R.id.ll_file,R.id.ll_voice_call})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_send:
                sendTextMessage(mEtMessage.getText().toString());
                mEtMessage.getText().clear();
                break;
            case R.id.ll_photo:
                PictureFileUtil.openGalleryPic(SingleChatActivity.this,REQUEST_CODE_IMAGE);
                break;
            case R.id.ll_video:
                PictureFileUtil.openGalleryAudio(SingleChatActivity.this, REQUEST_CODE_VIDEO);
                break;
            case R.id.ll_file:
                PictureFileUtil.openFile(SingleChatActivity.this,REQUEST_CODE_FILE);
                break;
            case R.id.ll_location:
                break;
            case R.id.ll_voice_call:
//                startActivity(RtcChatActivity.class);
                break;
            default:break;
        }
    }

    private void playAudioMsg(View view,Message message){
        AudioMsgBody audioMsgBody = (AudioMsgBody) message.getBody();
        final  boolean isSend = message.getSenderId().equals(mSenderId);
        if (mIvMsgAudio != null) {
            if (isSend){
                mIvMsgAudio.setBackgroundResource(R.mipmap.audio_animation_list_right_3);
            }else {
                mIvMsgAudio.setBackgroundResource(R.mipmap.audio_animation_list_left_3);
            }
            mIvMsgAudio = null;
            MediaManager.reset();
        }else{
            mIvMsgAudio = view.findViewById(R.id.ivAudio);
            MediaManager.reset();
            if (isSend){
                mIvMsgAudio.setBackgroundResource(R.drawable.audio_animation_right_list);
            }else {
                mIvMsgAudio.setBackgroundResource(R.drawable.audio_animation_left_list);
            }
            AnimationDrawable drawable = (AnimationDrawable) mIvMsgAudio.getBackground();
            drawable.start();
            MediaManager.playSound(SingleChatActivity.this,audioMsgBody.getLocalPath(), mp -> {
                if (isSend){
                    mIvMsgAudio.setBackgroundResource(R.mipmap.audio_animation_list_right_3);
                }else {
                    mIvMsgAudio.setBackgroundResource(R.mipmap.audio_animation_list_left_3);
                }

                MediaManager.release();
            });
        }
    }

    /**
     * Dispatch incoming result to the correct fragment.
     *
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case REQUEST_CODE_FILE:
                    String filePath = data.getStringExtra(FilePickerActivity.RESULT_FILE_PATH);
                    LogUtil.d("获取到的文件路径:"+filePath);
                    List<File> fileList = new ArrayList<>(1);
                    if (filePath != null) {
                        fileList.add(FileUtils.getFileByPath(filePath));
                        sendFileMessage(fileList);
                    }
                    break;
                case REQUEST_CODE_IMAGE:
                    // 图片选择结果回调
                    List<LocalMedia> selectListPic = PictureSelector.obtainMultipleResult(data);
                    List<File> imageList = new ArrayList<>(selectListPic.size());
                    for (LocalMedia media : selectListPic) {
                        LogUtil.d("获取图片路径成功:"+  media.getCompressPath());
                        File file = new File(media.getCompressPath());
                        imageList.add(file);
                    }
                    sendImageMessage(imageList);
                    break;
                case REQUEST_CODE_VIDEO:
                    // 视频选择结果回调
                    List<LocalMedia> selectListVideo = PictureSelector.obtainMultipleResult(data);
                    List<File> videoList = new ArrayList<>(selectListVideo.size());
                    for (LocalMedia media : selectListVideo) {
                        LogUtil.d("获取视频路径成功:"+  media.getRealPath());
                        videoList.add(FileUtils.getFileByPath(media.getRealPath()));
                    }
                    sendVideoMessage(videoList);
                    break;
                default:break;
            }
        }
    }

    private AbstractMessageSender.TextMessageParam getTextMessageParam(MsgBody msgBody){
        AbstractMessageSender.TextMessageParam messageParam = AbstractMessageSender.TextMessageParam.builder().msgBody(msgBody).build();
        messageParam.setSenderId(mSenderId);
        messageParam.setTargetId(mCurrentFriend.getFriendLoginId());
        messageParam.setSingleChat(true);
        return messageParam;
    }

    private AbstractMessageSender.FileMessageParam getFileMessageParam(List<File> fileList,int fileType){
        AbstractMessageSender.FileMessageParam messageParam = AbstractMessageSender.FileMessageParam.builder().fileList(fileList).fileType(fileType).build();
        messageParam.setSenderId(mSenderId);
        messageParam.setTargetId(mCurrentFriend.getFriendLoginId());
        messageParam.setSingleChat(true);
        return messageParam;
    }

    private String buildMsgBodyExtra(){
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty(Constant.JSON_KEY_SENDER_AVATAR, userRemoteAvatarUrl);
        return jsonObject.toString();
    }

    private void sendTextMessage(String msg) {
        TextMsgBody textMsgBody = new TextMsgBody();
        textMsgBody.setMessage(msg);
        String extra = buildMsgBodyExtra();
        Log.i(TAG, "sendTextMessage: " + extra);
        textMsgBody.setExtra(extra);
        presenter.sendTextMessage(getTextMessageParam(textMsgBody));
    }

    //图片消息
    private void sendImageMessage(List<File> fileList) {
        presenter.sendFileMessage(getFileMessageParam(fileList, HttpFilesUtil.IMAGE), new AbstractMessageSender.OnUploadListener() {
            @Override
            public MsgBody beforeUploadConvert(File file) {
                ImageMsgBody mImageMsgBody=new ImageMsgBody();
                mImageMsgBody.setThumbUrl(file.getAbsolutePath());
                String extra = buildMsgBodyExtra();
                Log.i(TAG, "beforeUploadConvert: " + extra);
                mImageMsgBody.setExtra(extra);
                return mImageMsgBody;
            }

            @Override
            public void onSucceed(Message message, String url) {
                ((ImageMsgBody) message.getBody()).setRemoteUrl(url);
            }

            @Override
            public void onFailed(String msgId) {
                onMessageSentFailed(msgId,null);
            }
        });
    }

    /**
     * 视频消息
     */
    private void sendVideoMessage(List<File> fileList) {
        presenter.sendFileMessage(getFileMessageParam(fileList, HttpFilesUtil.VIDEO), new AbstractMessageSender.OnUploadListener() {
            @Override
            public MsgBody beforeUploadConvert(File file) {
                VideoMsgBody mVideoMsgBody=new VideoMsgBody();
                String path = file.getAbsolutePath();
                mVideoMsgBody.setLocalPath(path);
                mVideoMsgBody.setDisplayName(FileUtils.getFileName(path));
                mVideoMsgBody.setSize(FileUtils.getFileLength(path));
                String extra = buildMsgBodyExtra();
                Log.i(TAG, "sendVideoMessage: " + extra);
                mVideoMsgBody.setExtra(extra);
                return mVideoMsgBody;
            }

            @Override
            public void onSucceed(Message message, String url) {
                ((VideoMsgBody) message.getBody()).setRemoteUrl(url);
            }

            @Override
            public void onFailed(String msgId) {
                onMessageSentFailed(msgId,null);
            }
        });
    }

    //文件消息
    private void sendFileMessage(List<File> fileList) {
        presenter.sendFileMessage(getFileMessageParam(fileList, HttpFilesUtil.FILE), new AbstractMessageSender.OnUploadListener() {
            @Override
            public MsgBody beforeUploadConvert(File file) {
                FileMsgBody mFileMsgBody=new FileMsgBody();
                String path = file.getAbsolutePath();
                mFileMsgBody.setLocalPath(path);
                mFileMsgBody.setDisplayName(FileUtils.getFileName(path));
                mFileMsgBody.setSize(FileUtils.getFileLength(path));
                String extra = buildMsgBodyExtra();
                Log.i(TAG, "sendFileMessage: " + extra);
                mFileMsgBody.setExtra(extra);
                return mFileMsgBody;
            }

            @Override
            public void onSucceed(Message message, String url) {
                ((FileMsgBody) message.getBody()).setRemoteUrl(url);
            }

            @Override
            public void onFailed(String msgId) {
                onMessageSentFailed(msgId,null);
            }
        });
    }

    /**
     * 语音消息
     */
    private void sendAudioMessage(String path,int time) {
        presenter.sendFileMessage(getFileMessageParam(new ArrayList<File>() {{
            add(FileUtils.getFileByPath(path));
        }}, HttpFilesUtil.AUDIO), new AbstractMessageSender.OnUploadListener() {
            @Override
            public MsgBody beforeUploadConvert(File file) {
                AudioMsgBody mAudioMsgBody=new AudioMsgBody();
                mAudioMsgBody.setLocalPath(path);
                mAudioMsgBody.setDuration(time);
                String extra = buildMsgBodyExtra();
                mAudioMsgBody.setExtra(extra);
                return mAudioMsgBody;
            }

            @Override
            public void onSucceed(Message message, String url) {
                ((AudioMsgBody) message.getBody()).setRemoteUrl(url);
            }

            @Override
            public void onFailed(String msgId) {
                onMessageSentFailed(msgId,null);
            }
        });
    }


    private Message getBaseSendMessage(MsgType msgType) {
        Message mMessage=new Message();
        mMessage.setMsgId(UUID.randomUUID().toString());
        mMessage.setUuid(UUID.randomUUID().toString());
        mMessage.setSenderId(mSenderId);
        mMessage.setTargetId(mCurrentFriend.getFriendLoginId());
        mMessage.setSentTime(System.currentTimeMillis());
        mMessage.setSentStatus(MsgSendStatus.SENDING);
        mMessage.setMsgType(msgType);
        return mMessage;
    }

    private Message getBaseReceiveMessage(MsgType msgType){
        Message mMessage=new Message();
        mMessage.setUuid(UUID.randomUUID()+"");
        mMessage.setSenderId(mCurrentFriend.getFriendLoginId());
        mMessage.setTargetId(mSenderId);
        mMessage.setSentTime(System.currentTimeMillis());
        mMessage.setSentStatus(MsgSendStatus.SENDING);
        mMessage.setMsgType(msgType);
        return mMessage;
    }

    @Override
    public void updateMsg(final Message mMessage) {
        mAdapter.addData(mMessage);
        mRvChatMsgList.scrollToPosition(mAdapter.getItemCount() - 1);
    }

    private void changeMsgStatus(String msgId,MsgSendStatus sendStatus){
        ThreadPoolUtil.runOnMainThread(() -> {
            int position=mAdapter.getItemCount() - 1;
            //更新单个子条目
            for (int i=position;i!=0;i--){
                Message mAdapterMessage=mAdapter.getItem(i);
                if (msgId.equals(mAdapterMessage.getMsgId())){
                    position=i;
                    break;
                }
            }
            mAdapter.getItem(position).setSentStatus(sendStatus);
            mAdapter.notifyDataSetChanged();
        });
    }

    @Override
    public void showLoading() {

    }

    @Override
    public void hideLoading() {

    }

    /**
     * Called when a swipe gesture triggers a refresh.
     */
    @Override
    public void onRefresh() {
        //下拉刷新模拟获取历史消息
        List<Message>  mReceiveMsgList= new ArrayList<>();
        //构建文本消息
        Message mMessgaeText=getBaseReceiveMessage(MsgType.TEXT);
        TextMsgBody mTextMsgBody=new TextMsgBody();
        mTextMsgBody.setMessage("收到的消息");
        mMessgaeText.setBody(mTextMsgBody);
        mMessgaeText.setSentTime(System.currentTimeMillis());
        mReceiveMsgList.add(mMessgaeText);
        //构建图片消息
        Message mMessgaeImage=getBaseReceiveMessage(MsgType.IMAGE);
        ImageMsgBody mImageMsgBody=new ImageMsgBody();
        mImageMsgBody.setThumbUrl("https://c-ssl.duitang.com/uploads/item/201208/30/20120830173930_PBfJE.thumb.700_0.jpeg");
        mMessgaeImage.setBody(mImageMsgBody);
        mMessgaeImage.setSentTime(System.currentTimeMillis());
        mReceiveMsgList.add(mMessgaeImage);
        //构建文件消息
        Message mMessgaeFile=getBaseReceiveMessage(MsgType.FILE);
        FileMsgBody mFileMsgBody=new FileMsgBody();
        mFileMsgBody.setDisplayName("收到的文件");
        mFileMsgBody.setSize(12);
        mMessgaeFile.setBody(mFileMsgBody);
        mMessgaeFile.setSentTime(System.currentTimeMillis());
        mReceiveMsgList.add(mMessgaeFile);
        mAdapter.addData(0,mReceiveMsgList);
        mSwipeRefreshLayout.setRefreshing(false);
    }

    /**
     * 订阅事件，并处理
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(MessageEvent event){
        switch (event.getEventType()){
            case SINGLE_CHAT_MSG:
                Message message = (Message) event.getData();
                updateMsg(message);
                presenter.saveChatMsg(MessageConverter.toMessagePo(message, true));
                break;
            case GROUP_CHAT_MSG:
            case DOWNLOAD_COMPLETE:
            case UPLOAD_COMPLETE:
            case ADD_FRIEND_MSG:
            default:break;
        }
    }

    @Override
    protected void destroy() {
        GradientStatusBarUtil.getInstance().unbind();
        EventBus.getDefault().unregister(this);
        ImClientBoot.getInstance().setOnMessageStatusListener(null);
        super.destroy();
    }

    @Override
    public void onMessageSentSucceed(String msgId) {
        changeMsgStatus(msgId,MsgSendStatus.SENT);
    }

    @Override
    public void onMessageSending(String msgId) {
        System.out.println(msgId);
    }

    @Override
    public void onMessageSentFailed(String msgId, Object cause) {
        changeMsgStatus(msgId,MsgSendStatus.FAILED);
    }
}